如本日主題,今天要來介紹一下Go語言的程式碼架構,以下內容摘錄自『 The Go Workshop 』。
package main ...................................................Part 1
import (........................................................Part 2
"errors"
"fmt"
"log"
"math/rand"
"strconv"
"time"
)
var helloList = []string{.......................................Part 3
"Hello, world",
"Καλημέρα κόσμε",
"こんにちは世界",
" ایند مالس",
"Привет, мир",
}
func main() {...................................................Part 4
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(helloList))
msg, err := hello(index)
if err != nil {
log.Fatal(err)
}
fmt.Println(msg)
}
func hello(index int) (string, error) {.........................Part 5
if index < 0 || index > len(helloList)-1 {
return "", errors.New("out of range: " + strconv.Itoa(index))
}
return helloList[index], nil
}
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"strconv"
"time"
)
var helloList = []string{
"Hello, world",
"Καλημέρα κόσμε",
"こんにちは世界",
" ایند مالس",
"Привет, мир",
}
func main() {
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(helloList))
msg, err := hello(index)
if err != nil {
log.Fatal(err)
}
fmt.Println(msg)
}
func hello(index int) (string, error) {
if index < 0 || index > len(helloList)-1 {
return "", errors.New("out of range: " + strconv.Itoa(index))
}
return helloList[index], nil
}